package com.starhub.domain.ai.controller;

import com.starhub.application.agent.dto.AIChatInfo;
import com.starhub.application.agent.service.IChatService;
import com.starhub.application.agent.service.IModelService;
import com.starhub.common.bean.ResultResp;
import com.starhub.common.exception.AppException;
import com.starhub.integration.sdk.shangtang.model.ShangtangChatModel;

import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/starhub/ai")
public class ChatDeepSeekController {

    private static final Logger log = LoggerFactory.getLogger(ChatDeepSeekController.class);

    @Autowired
    private IModelService modelService;

    @Autowired
    private IChatService chatService;
    
    @GetMapping("/generate")
    public ResultResp<String> generate(@RequestParam(value = "mark") String mark, @RequestParam(value = "message") String message) {
        try {
            return ResultResp.success(modelService.call(mark,message));
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            return ResultResp.fail(e.getMessage(),e);
        }
    }

    /**  
     * 流式返回 ChatGPT 的消息响应  
     *  
     * @param mark 模型标识
     * @param message 用户输入的消息  
     * @return SseEmitter 用于流式推送数据到客户端  
     */  
    @RequestMapping("/stream")
    public void streamChat(@RequestParam(value = "mark") String mark, @RequestParam(value = "message") String message, HttpServletResponse response) throws Exception {
        AIChatInfo aiChatInfo = new AIChatInfo();
        aiChatInfo.setSelectedModel(mark);
        aiChatInfo.setUserMessage(message);
        aiChatInfo.setAgentId(1L);
        aiChatInfo.setUserId("1");
        aiChatInfo.setSessionId("hhj_01");


        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Connection", "keep-alive");

        chatService.chatStream(aiChatInfo,  response.getWriter());
    }

    /**  
     * 流式返回公文生成的消息响应  
     *  
     * @param pageLength 输入长度
     * @param odocTypeName 文档类型
     * @param topicType 公文标题
     * @param keywords 关键字
     * @param sessionId 会话ID
     * @return SseEmitter 用于流式推送数据到客户端  
     */  
    @GetMapping("/streamOdoc")  
    public SseEmitter streamOdoc(
            @RequestParam(value = "page_length") int pageLength,
            @RequestParam(value = "odocTypeName") String odocTypeName,
            @RequestParam(value = "topic_type") String topicType,
            @RequestParam(value = "keywords") String keywords,
            @RequestParam(value = "sessionId") String sessionId) {
        
        // 创建 AIChatInfo 对象
        AIChatInfo chatInfo = new AIChatInfo();
        chatInfo.setSessionId(sessionId);
        // 构建提示词
        String prompt = String.format("帮我起草一篇公文，直接帮我返回公文内容，不要返回其他信息");
        chatInfo.setUserMessage(prompt);
        chatInfo.setAgentId(1111102L);
        // 设置额外参数
        Map<String, Object> additionalParams = new HashMap<>();
        additionalParams.put("page_length", pageLength);
        additionalParams.put("odocTypeName", odocTypeName);
        additionalParams.put("topic_type", topicType);
        additionalParams.put("keywords", keywords);
        additionalParams.put("supplement", "");
        additionalParams.put("main_unit", "办公室");
        additionalParams.put("send_unit", "办公室");
        



        chatInfo.setAdditionalParams(additionalParams);
        
        return chatService.chatStream(chatInfo); 
    }



    @GetMapping("/generateST")
    public ResultResp<String> generateST(@RequestParam(value = "message") String message,@RequestParam(value = "model") String model) {
        try {
            ShangtangChatModel chatModel = new ShangtangChatModel(
                    "http://192.168.110.109:18001/v1/chat/completions",
                    model,
                    0.7,
                    1024
            );
            String response = chatModel.generate(message);
            return ResultResp.success(response);
        } catch (Exception e) {
            return ResultResp.fail(e.getMessage(),e);
        }
    }
}
